package com.xdxc.controller;

import com.xdxc.JwtGenaner.JwtUtil;
import com.xdxc.store.ClientStore;
import com.xdxc.utils.HmacUtil;
import com.xdxc.utils.JWTUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;



@RestController
@RequestMapping("/client")
public class ClientAuthController {

    private static final long MAX_TIMESTAMP_DIFF = 5 * 60 * 1000; // 5 分钟

    private final ClientStore clientStore;

    public ClientAuthController(ClientStore clientStore) {
        this.clientStore = clientStore;
    }

    @PostMapping("/token")
    public ResponseEntity<?> issueToken(@RequestParam("clientId") String clientId,
                                        @RequestParam("Timestamp") String timestampStr,
                                        @RequestParam("clientSecret") String signature) {


        if (clientId == null || timestampStr == null || signature == null) {
            return ResponseEntity.badRequest().body("Missing authentication headers");
        }

        long timestamp;
        try {
            timestamp = Long.parseLong(timestampStr);
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body("Invalid timestamp");
        }

        // 检查时间戳时效
        long now = System.currentTimeMillis();
        if (Math.abs(now - timestamp) > MAX_TIMESTAMP_DIFF) {
            return ResponseEntity.status(401).body("Timestamp expired");
        }

        // 校验签名
        String secret = clientStore.getSecret(clientId);
        if (secret == null ||
                !HmacUtil.verify(clientId + "|" + timestampStr, secret, signature)) {
            return ResponseEntity.status(401).body("Invalid signature");
        }

        // TODO: 从客户端配置或 DB 中读取该 clientId 的角色


        List<String> roles = List.of("SERVICE");

        String token = JwtUtil.generateToken(clientId,10001L ,roles);
        return ResponseEntity.ok(Map.of(
                "access_token", token,
                "token_type", "Bearer",
                "expires_in", 3600
        ));
    }
}

